package com.health.ts.utils;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

/**
 * Created on 2018年4月3日
 * <p>
 * Description {通用校验工具}
 * <p>
 * Copyright neusoft (c) 2015 .
 * 
 * @author wangjili@neusoft.com
 *
 */
public class ValidatorUtil {

	/**
	 * Created on 2018年4月3日 .
	 * 
	 * @param obj
	 * @return {校验}
	 */
	public static <T> Set<ConstraintViolation<T>> validate(T obj) {
		Validator validator = ApplicationContextUtil.getBean(Validator.class);
		return validator.validate(obj);
	}

	/**
	 * Created on 2018年4月3日 . 分组校验
	 * 
	 * @param obj
	 * @param groups
	 * @return {描述}
	 */
	public static <T> Set<ConstraintViolation<T>> validate(T obj, Class<?>... groups) {
		Validator validator = ApplicationContextUtil.getBean(Validator.class);
		return validator.validate(obj, groups);
	}

	/**
	 * Created on 2018年4月3日 .
	 * 
	 * @param obj
	 * @return {将校验结果转换为错误描述}
	 */
	public static <T> String getErrorMessage(Set<ConstraintViolation<T>> violations) {
		if (violations == null || violations.isEmpty()) {
			return null;
		}

		StringBuilder sb = new StringBuilder();
		int index = 1;
		for (ConstraintViolation<T> violation : violations) {
			sb.append(String.format("%s. 错误项：%s 错误内容：%s\r\n", index, violation.getPropertyPath().toString(), violation.getMessage()));
			index += 1;
		}
		return sb.toString();
	}

	/**
	 * Created on 2018年4月3日 . 获取校验结果
	 * 
	 * @param obj
	 * @return {描述}
	 */
	public static <T> String getErrorDetailByValidate(T obj) {
		Set<ConstraintViolation<T>> violations = validate(obj);
		return getErrorMessage(violations);
	}

	/**
	 * Created on 2018年4月3日 . 获取校验结果
	 * 
	 * @param obj
	 * @return {描述}
	 */
	public static <T> String getErrorDetailByValidate(T obj, Class<?>... groups) {
		Set<ConstraintViolation<T>> violations = validate(obj, groups);
		return getErrorMessage(violations);
	}
}
